<template>
  <div class="register-container">
    <div class="background-shapes">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
      <div class="shape shape-3"></div>
      <div class="shape shape-4"></div>
    </div>
    
    <div class="register-wrapper">
      <div class="register-header">
        <div class="logo">
          <svg class="cloud-icon" viewBox="0 0 24 24" width="32" height="32">
            <path fill="#409EFF" d="M19 16.5a4.5 4.5 0 0 0-4.5-4.5H14a6 6 0 1 0-8 5.7v.3a2.5 2.5 0 0 0 0 5h13a4.5 4.5 0 0 0 0-9z"/>
          </svg>
          <h1 class="brand-title">加入云自习室</h1>
        </div>
        <p class="welcome-text">开启你的专注学习之旅</p>
      </div>

      <el-card class="register-card" shadow="hover">
        <el-form ref="registerFormRef" :model="registerForm" :rules="rules" label-position="top">
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="registerForm.username" 
              placeholder="请输入用户名" 
              size="large"
              prefix-icon="User"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="registerForm.email" 
              placeholder="请输入邮箱地址" 
              size="large"
              prefix-icon="Message"
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="registerForm.password" 
              type="password" 
              placeholder="请输入密码" 
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input 
              v-model="registerForm.confirmPassword" 
              type="password" 
              placeholder="请再次输入密码" 
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="agreementChecked" class="agreement-checkbox">
              我已阅读并同意
              <el-button type="text" class="agreement-link">《用户协议》</el-button>
              和
              <el-button type="text" class="agreement-link">《隐私政策》</el-button>
            </el-checkbox>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleRegister" 
              size="large"
              class="register-btn"
              :loading="loading"
              :disabled="!agreementChecked"
            >
              <span v-if="!loading">立即注册</span>
              <span v-else>注册中...</span>
            </el-button>
          </el-form-item>
        </el-form>

        <div class="register-footer">
          <div class="login-link">
            已有账号？
            <el-button type="text" @click="$router.push('/login')" class="login-btn">
              立即登录
            </el-button>
          </div>
          
          <div class="benefits">
            <h4 class="benefits-title">注册即可享受</h4>
            <div class="benefit-list">
              <div class="benefit-item">
                <el-icon class="benefit-icon"><Clock /></el-icon>
                <span>免费番茄时钟</span>
              </div>
              <div class="benefit-item">
                <el-icon class="benefit-icon"><UserFilled /></el-icon>
                <span>学习小组功能</span>
              </div>
              <div class="benefit-item">
                <el-icon class="benefit-icon"><TrendCharts /></el-icon>
                <span>学习数据统计</span>
              </div>
              <div class="benefit-item">
                <el-icon class="benefit-icon"><Trophy /></el-icon>
                <span>成就徽章系统</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { User, Message, Lock, Clock, UserFilled, TrendCharts, Trophy } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const store = useStore()
const registerFormRef = ref(null)
const loading = ref(false)
const agreementChecked = ref(false)

const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.value.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validateUsername = async (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (value.length < 3) {
    callback(new Error('用户名至少3个字符'))
  } else if (value.length > 20) {
    callback(new Error('用户名最多20个字符'))
  } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error('用户名只能包含字母、数字、下划线和中文'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, validator: validateUsername, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码需包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  if (!agreementChecked.value) {
    ElMessage.warning('请先同意用户协议和隐私政策')
    return
  }

  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      const { username, email, password } = registerForm.value
      
      try {
        const response = await axios.post('/api/users/register/', {
          username,
          email,
          password
        })
        
        if (response.status === 201) {
          ElMessage.success('注册成功！欢迎加入云自习室')
          router.push('/login')
        } else {
          ElMessage.error(response.data?.message || '注册失败')
        }
      } catch (err) {
        console.error('注册失败:', err)
        if (err.response?.status === 400) {
          const errorData = err.response.data
          if (errorData.username) {
            ElMessage.error('用户名已存在')
          } else if (errorData.email) {
            ElMessage.error('邮箱已被注册')
          } else {
            ElMessage.error('注册信息有误，请检查后重试')
          }
        } else {
          ElMessage.error(err.response?.data?.message || '网络错误，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.error('请正确填写所有信息')
    }
  })
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.background-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.shape {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: float 8s ease-in-out infinite;
}

.shape-1 {
  width: 180px;
  height: 180px;
  top: 5%;
  left: 5%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 20%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 200px;
  height: 200px;
  bottom: 10%;
  left: 20%;
  animation-delay: 4s;
}

.shape-4 {
  width: 150px;
  height: 150px;
  bottom: 20%;
  right: 5%;
  animation-delay: 6s;
}

@keyframes float {
  0%, 100% { 
    transform: translateY(0px) translateX(0px) rotate(0deg); 
  }
  25% { 
    transform: translateY(-15px) translateX(10px) rotate(5deg); 
  }
  50% { 
    transform: translateY(-25px) translateX(-5px) rotate(-5deg); 
  }
  75% { 
    transform: translateY(-10px) translateX(-10px) rotate(3deg); 
  }
}

.register-wrapper {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 480px;
}

.register-header {
  text-align: center;
  margin-bottom: 32px;
  color: white;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 16px;
}

.cloud-icon {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.brand-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.welcome-text {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  font-weight: 300;
}

.register-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.register-card :deep(.el-card__body) {
  padding: 0;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item :deep(.el-form-item__label) {
  color: #303133;
  font-weight: 500;
  margin-bottom: 8px;
}

.el-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

.el-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.agreement-checkbox {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.agreement-checkbox :deep(.el-checkbox__label) {
  font-size: 14px;
}

.agreement-link {
  color: #409eff;
  font-size: 14px;
  padding: 0;
  text-decoration: underline;
}

.register-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #409eff 0%, #667eea 100%);
  border: none;
  transition: all 0.3s;
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(64, 158, 255, 0.3);
}

.register-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.register-footer {
  margin-top: 24px;
}

.login-link {
  text-align: center;
  color: #606266;
  font-size: 14px;
  margin-bottom: 24px;
}

.login-btn {
  color: #409eff;
  font-weight: 500;
  padding: 0 4px;
}

.login-btn:hover {
  color: #667eea;
}

.benefits {
  padding-top: 20px;
  border-top: 1px solid #f0f2f6;
}

.benefits-title {
  text-align: center;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 16px 0;
}

.benefit-list {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.benefit-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 13px;
}

.benefit-icon {
  color: #409eff;
  font-size: 16px;
}

@media (max-width: 480px) {
  .register-container {
    padding: 16px;
  }
  
  .register-card {
    padding: 24px 20px;
  }
  
  .brand-title {
    font-size: 24px;
  }
  
  .benefit-list {
    grid-template-columns: 1fr;
  }
  
  .agreement-checkbox {
    font-size: 13px;
  }
}
</style>